<template>
  <div class="logo" style="margin:0 auto; width: 600px; margin-top: 100px;">
    <img src="../assets/logo.png" alt="" style="width: auto; height: auto; margin-left: 20px;">
  </div>
  <div class="register">
    <h1 style="text-align: center;">手机号注册</h1>
    <el-form :model="user" label-width="auto" style="width: 300px; padding-left: 150px; ">
    <el-form-item>
      <el-input v-model="user.mobile" placeholder="手机号" />
    </el-form-item>
    <el-form-item>
      <el-input v-model="user.sms_code" placeholder="验证码" />
    </el-form-item>
  </el-form>
  <el-button type="primary" @click="send_sms">发送验证码</el-button>
  <el-button type="primary" @click="register">注册</el-button><br><br>
  <el-button type="primary" @click="router.push('/')">已有账号？点击登录</el-button><br><br>
  <el-button type="primary" @click="router.push('/register')">使用用户名密码注册</el-button>
  </div>
  
</template>

<style scoped>
  .register{
    width: 600px;
    height: 400px;
    margin: 0 auto;
    text-align: center;
    border: 2px solid black;
    border-radius: 10px;
  }
</style>

<script setup>
  import { ref, onMounted } from "vue"
  import axios from "axios"
  import { useRoute, useRouter } from "vue-router";

  const route = useRoute()
  const router = useRouter()

  let user = ref({
    mobile: "",
    sms_code: "",
  })

  const send_sms=()=>{
    if(user.value.mobile === ""){
      alert("请输入手机号")
    }
    else{
      axios.post(`http://127.0.0.1:8000/user/sendSms/`, {mobile: user.value.mobile})
      .then(res=>{
        console.log(res)
      })
      .catch(error=>{
        console.log(error)
        if(error.response.data.data === "手机号格式错误"){
          alert("手机号格式错误")
        }
        else if(error.response.data.data === "该手机号已注册"){
          alert("该手机号已注册")
        }
        else if(error.response.data.data === "验证码仍在有效期内，请勿频繁请求"){
          alert("验证码仍在有效期内，请勿频繁请求")
        }
      })
    }
  }

  const register=()=>{
    if(user.value.sms_code === ""){
      alert("请输入验证码")
    }
    else{
      axios.post(`http://127.0.0.1:8000/user/smsRegister/`, user.value)
      .then(res=>{
        console.log(res)
        localStorage.setItem("access_token", res.data.token)
        localStorage.setItem("refresh_token", res.data.refresh)
        router.push("/homepage")
      })
      .catch(error=>{
        console.log(error)
        if("non_field_errors" in error.response.data && error.response.data.non_field_errors[0] === "验证码输入错误，请重新输入"){
          alert("验证码输入错误，请重新输入")
        }
      })
    }
  }

</script>
